﻿#include "debug.h"
#include "sys_plat.h"
#include <stdarg.h>

/**
 * @brief debug日志打印
 * @param level 日志打印等级
 * @param slevel 设定的日志打印等级
 */
void dbg_print(int level, int slevel, const char *file, const char *func, const int line, const char *fmt, ...)
{
    if (level > slevel)
        return;

    // 新写法，学到了o(*￣▽￣*)ブ
    const char *title[] = {
        [DBG_LEVEL_NONE] = "",
        [DBG_LEVEL_ERROR] = DBG_STYLE_ERROR "[ERROR]",
        [DBG_LEVEL_WARNING] = DBG_STYLE_WARNING "[WARNING]",
        [DBG_LEVEL_INFO] = "[INFO]"};

    // 由于传入的file是整个文件的名称，需要进行处理
    const char *end = file + plat_strlen(file);
    while (end >= file)
    {
        if ((*end == '\\') || (*end == '/'))
        {
            break;
        }
        --end;
    }
    ++end;
    plat_printf("%s%s-%s-%d: ", title[level], end, func, line);
    // plat_printf("%s-%s-%d: ", end, func, line);

    char print_buf[1024];
    plat_memset(print_buf, 0, sizeof(print_buf));
    va_list args;
    va_start(args, fmt);
    plat_vsprintf(print_buf, fmt, args);
    va_end(args);

    plat_printf("%s\n" DBG_STYLE_RESET, print_buf);

    return;
}

void dbg_dump_ipaddr(const char *msg, const struct _ipaddr_t *ipaddr)
{
    if (msg)
        plat_printf("%s", msg);
    if (ipaddr)
    {
        plat_printf("%d.%d.%d.%d\n", ipaddr->addr[IPV4_ADDR_FIRST], ipaddr->addr[IPV4_ADDR_SECOND], ipaddr->addr[IPV4_ADDR_THIRD], ipaddr->addr[IPV4_ADDR_FOURTH]);
    }
    else
    {
        plat_printf("0.0.0.0\n");
    }
}

void dbg_dump_hwaddr(const char *msg, const uint8_t *hwaddr, int len)
{
    if (msg)
        plat_printf(msg);
    if (hwaddr)
    {
        for (int i = 0; i < len; ++i)
        {
            plat_printf("%02x", hwaddr[i]);
            if (i != len - 1)
                plat_printf("-");
        }
    }
    else
    {
        plat_printf("????????");
    }
    plat_printf("\n");
}

void dbg_dump_hwaddr_oneline(const char *msg, const uint8_t *hwaddr, int len)
{
    if (msg)
        plat_printf(msg);
    if (hwaddr)
    {
        for (int i = 0; i < len; ++i)
        {
            plat_printf("%02x", hwaddr[i]);
            if (i != len - 1)
                plat_printf("-");
        }
    }
    else
    {
        plat_printf("????????");
    }
}


void dbg_dump_ipaddr_oneline(const char *msg, const struct _ipaddr_t *ipaddr)
{
    if (msg)
        plat_printf("%s", msg);
    if (ipaddr)
    {
        plat_printf("%3d.%3d.%3d.%3d", ipaddr->addr[IPV4_ADDR_FIRST], ipaddr->addr[IPV4_ADDR_SECOND], ipaddr->addr[IPV4_ADDR_THIRD], ipaddr->addr[IPV4_ADDR_FOURTH]);
    }
    else
    {
        plat_printf("  0.  0.  0.  0");
    }
}